
// b 是 矩形的半宽+半高
float my_sd_box( in vec2 p, in vec2 b ) {
    vec2 d = abs( p ) - b;
    // return length(  )
    return 1.0;
}


// 使用了转化到第一象限进行半宽半高比较; 注意划分的三个区域 
// 1. 内部 2. 外部但是在正上方(渲染的点的位置 x < Rect.w 小于宽度) 
// 3. 在正右方 ( p.y < Rect.h ); 4. 在右上角 ( p.x>Rect.w && p.y > Rect.h ) ---> 一个 max 就能实现
// 矩形中间区域 先 max( d.x, d.y ) 求最大负数 
float sdBox( in vec2 p, in vec2 b )
{
    vec2 d = abs(p)-b;
    return length(max(d,0.0)) + min(max(d.x,d.y),0.0);
    /*
        返回值 > 0 在外部
        返回值 < 0 在内部
    */
}


float sdSegment( in vec2 p, in vec2 a, in vec2 b )
{
    vec2 pa = p-a, ba = b-a;
    float h = clamp( dot(pa,ba)/dot(ba,ba), 0.0, 1.0 );
    return length( pa - ba*h );
}

float sdPentagram(in vec2 p, in float r )
{
    const float k1x = 0.809016994; // cos(π/ 5) = ¼(√5+1)
    const float k2x = 0.309016994; // sin(π/10) = ¼(√5-1)
    const float k1y = 0.587785252; // sin(π/ 5) = ¼√(10-2√5)
    const float k2y = 0.951056516; // cos(π/10) = ¼√(10+2√5)
    const float k1z = 0.726542528; // tan(π/ 5) = √(5-2√5)
    const vec2  v1  = vec2( k1x,-k1y);
    const vec2  v2  = vec2(-k1x,-k1y);
    const vec2  v3  = vec2( k2x,-k2y);
    
    p.x = abs(p.x);
    p -= 2.0*max(dot(v1,p),0.0)*v1;
    p -= 2.0*max(dot(v2,p),0.0)*v2;
    p.x = abs(p.x);
    p.y -= r;
    return length(p-v3*clamp(dot(p,v3),0.0,k1z*r))
           * sign(p.y*v3.x-p.x*v3.y);
}

void main () {
    vec2 uv = ( gl_FragCoord.xy - 0.5*iResolution.xy )*2.0 / iResolution.xy;
    float d = sdBox( uv-vec2( 0.1, -0.3 ), vec2( 0.3, 0.4 ) );
    // d = smoothstep( .0, .01, abs(d)  );
    d = smoothstep( .0, .01, d  );

    float d_segment = sdSegment( uv, vec2(0.4), vec2( 0.1, 0.2 ) );
    d_segment = smoothstep( .0, .02, d_segment );
    // 使用 并集 来添加多个 sdf 图形
    d =  min( d, d_segment );

    float d_pentagram = sdPentagram( uv - ( -0.4, -0.4 ), 0.2 );
    d_pentagram = smoothstep( .0, .01, d_pentagram );
    d= min( d, d_pentagram );

    gl_FragColor = vec4( d, d, d, 1.0 );
    return ;
}